//
//  XYBookDetailsController.swift
//  XYReadBook
//
//  Created by fox on 2017/9/7.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

/// 书籍详情信息
class XYBookDetailsController: XYViewController {
    var oldHeigth:CGFloat = 0
    var headerHeight:CGFloat = 350.0
    let stateString:String
    let bookID:String
    var dataArr:[XYIntroduceModel] = []
    var headerView:XYBookDetailsHeaderView!
    var model:XYBookDetailModel?
    {
        didSet {
            collectionView.reloadData()
        }
    }
    let Identifier = "BookDetailsdentifier"
    let headerIfier = "UICollectionElementKindSectionHeadersdentifier"
    let Layout = UICollectionViewFlowLayout()


    var collectionView:UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
          setupUI()
        if HTTPManager.isnetWorkBool() == false {
            let errorView = XYErrorView.init(frame: self.view.bounds, errorType: .errorNotWork)
            view.addSubview(errorView)
            weak var weakSelf = self
            errorView.overrideLoadData = {
                XYLog(messsage: "无网络,重新加载数据")
                  weakSelf?.loadData()
                  weakSelf?.loadIntroduceBook()
            }
        }else {
            loadIntroduceBook()
            loadData()
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.isNavigationBarHidden = false
    }
    
    init(bookID:String,stateString:String) {
        self.bookID = bookID
        self.stateString = stateString
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func loadData() {
        // http://api.zhuishushenqi.com/book/5106099abb1c67cf28000016

        let urlKey = String(format: "book/%@", self.bookID)
        let url =  XYAPI.baseurlFormat(baseURL: BaseUrl.defult.rawValue, key: urlKey)
        weak var weakSelf = self
        HTTPManager.requestModel(url: url, method: .get, parameters: nil, iscaChe: true) { (resp:XYBookDetailModel?, error) in
            if let resp = resp {
                 self.model = resp

            }else {
                XYLog(messsage: "网络加载失败")
            }
        }
    }
    
    
    /// 推荐
    // http://api.zhuishushenqi.com/book/50c00e34901245c74d000001/recommend?limit=10
    private  func loadIntroduceBook() {
        let urlKey = String(format: "book/%@/recommend?limit=10", self.bookID)
        let url =  XYAPI.baseurlFormat(baseURL: BaseUrl.defult.rawValue, key: urlKey)
        
        HTTPManager.requestModel(url: url, method: .get, parameters: nil, iscaChe: false) { (resp:XYIntroduceBookModel?, error) in
            if let resp = resp {
                self.dataArr = resp.books
                self.collectionView.reloadData()
            }
        }
    }
    
    
    func setupUI () {
        collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: Layout)
        Layout.scrollDirection = UICollectionViewScrollDirection.vertical
        Layout.itemSize = CGSize.init(width: ((ScreenWidth - 70) / 3), height: 150)
        //垂直方向间距
        Layout.minimumInteritemSpacing = 0
        Layout.minimumLineSpacing = 10
        Layout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: headerHeight)

        //水平方向间距
        //设置四周得边缘距离
        Layout.sectionInset = UIEdgeInsetsMake(17.50, 17.5, 17.50, 17.5)
        //
        collectionView.register(XYBookDetailCell.self, forCellWithReuseIdentifier:Identifier)
        //
        collectionView.register(XYBookDetailsHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerIfier)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.white
        collectionView.bounces = false
        view.addSubview(collectionView)
        let item = UIBarButtonItem(title: "返回", style: .plain, target: self, action: nil)
        navigationItem.backBarButtonItem = item
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        collectionView.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight )
    }
    
    
    /// 计算文本高度
    ///
    /// - Parameters:
    ///   - textStr: 需要计算的字符串
    ///   - font: 给定的font
    ///   - width: 给指定的宽度
    /// - Returns: 指定宽度,所需要占用的高度
    public  func getTextHeigh(textStr:String,font:UIFont,width:CGFloat) -> CGFloat {
        
        let normalText: NSString = textStr as NSString
        let size = CGSize.init(width: width, height: 1000)
        let dic = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying)
        let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size
        return stringSize.height
    }
}


// MARK: - 实际项目中最好不要写感叹号! 万一没值就崩溃了
extension XYBookDetailsController:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    
    func  numberOfSections(in collectionView: UICollectionView) -> Int
    {
        return 1
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:Identifier, for: indexPath)as!XYBookDetailCell
        cell.backgroundColor = UIColor.hm_color(withRed: 242, green: 242, blue: 242)
        cell.model = dataArr[indexPath.row]
        return cell
    }
}

extension XYBookDetailsController:UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    }
    
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        // 在此

        headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIfier, for: indexPath) as!XYBookDetailsHeaderView

        headerView.model = self.model
        headerView.typeStr = self.stateString
        headerView.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: self.headerHeight)
        headerView.delegate = self
        return headerView
    }
}


extension XYBookDetailsController:XYBookDetailsHeaderViewDelegate {

    //设置协议方法
    func bookDetailsUpdateFrame(HeaderView:XYBookDetailsHeaderView) {
        // 计算文本高度

        if oldHeigth != 0 {
            headerHeight -= oldHeigth
            oldHeigth = 0
            Layout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: headerHeight)
            return
        }
        if let model = model {
            XYLog(messsage: model.longIntro)
            let text = String.init(format: "内容简介: %@", model.longIntro)
            let strW = ScreenWidth - 24
            let strHeight = getTextHeigh(textStr: text, font: UIFont.systemFont(ofSize: 15), width: strW)
            let newH = strHeight - 90
            self.headerHeight = headerHeight + newH
            oldHeigth = newH

            Layout.headerReferenceSize = CGSize.init(width: ScreenWidth, height:headerHeight)
            //         collectionView.setNeedsLayout()
        }
    }
    
    
    /// 跳转目录
    func bookDetailsGotoList(HeaderView:XYBookDetailsHeaderView) {

        if let model = model {
            let vc = XYBookListController.init(bookID: model.id,bookName:model.title)
            vc.hidesBottomBarWhenPushed = true
            vc.navigationItem.title = model.title
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    
    /// 点击阅读
    func bookDetailsReadBook(HeaderView:XYBookDetailsHeaderView) {
        
        if let title = model?.title {
            let bookModel = XYReadModel.init(bookID: bookID)
            let vc = XYReaderController.init(bookID: bookID,bookName:title,bookModel:bookModel,bookIcon:HeaderView.iconImage)
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    
    /// 直接跳转最后一章
    ///
    /// - Parameter HeaderView: 直接条跳转最后一个章节
    func bookDetailsGoToLastChapter(HeaderView:XYBookDetailsHeaderView){
        if let title = model?.title {
            let bookModel = XYReadModel.init(bookID: bookID)
            let vc = XYReaderController.init(bookID: bookID,bookName:title,bookModel:bookModel,bookIcon:HeaderView.iconImage)
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}

